using System;
using System.Collections;
using System.Data;
using System.IO;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Purchasing.Enumerations;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using Utils = PHSRAG.Insight21.InsightUtilities;

/*Bhaskar- 01/18/2008
 * This page is used to show  for SQL reports for purchasing
 * the actual implementation may be a little different
 */

namespace PHSRAG.Insight21.Purchasing
{
    public partial class sqlReportHost : BasePage
    {
        private string _pageUrl = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    //name of the report to serve up
                    string format = Request["fmt"]; //format of the report - PDF or Excel
                    string srptName = Request["rpt"];
                    _pageUrl = Request["pageUrl"];
                    //different Reports are accessed based on data in search criteria
                    Hashtable ht = GetInputParameters(ref srptName);

                    if (!string.IsNullOrEmpty(srptName))
                    {
                        SSRSRequest.FetchAndDisplayReport(format, srptName, ht);
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("There was a problem processing your request. Please contact helpdesk. <br>" + ex.Message);
                }
            }
        }

        # region InputParameters

        /// <summary>
        /// Set Report Name based on the search criteria  for reconciliation
        /// </summary>
        private void SetReportNameAndDataSetForReconciliation(ref string srptName, ref DataSet reportDataTable, ref string reporttitle, ref string recordcount)
        {
            ICachePolicy cachePolicy = (ICachePolicy) Session[Names.CachePolicyKey];
            CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
            SearchCriteria commonSearchCriteria = searchContext.GetSearchCriteria(Page.Request["pageUrl"]);
            int reconcileTypeID =
                Convert.ToInt32(commonSearchCriteria[InsightUtilities.Constants.PurchasingSearchKey.ReconcileTypeKey]);
            int orderTypeID =
                Convert.ToInt32(commonSearchCriteria[InsightUtilities.Constants.PurchasingSearchKey.UserOrderTypeViewKey]);

            if (orderTypeID == 0)
            {
                orderTypeID = (int) OrderType.PurchaseOrder; // default to POs
            }


            if (reconcileTypeID == (int) ReconcileType.Matched)
            {
                switch (orderTypeID)
                {
                    case (int) OrderType.PurchaseOrder:
                    case (int) OrderType.JournalEntry:
                    case (int) OrderType.PettyCash:

                        srptName = SSRSRequest.ReportNames.Purchasing.ReconciledMatchedPO; //"Pur_ReconcileMatched_PO";
                        break;

                    case (int) OrderType.TravelVoucher:
                    case (int) OrderType.ChequeRequest:

                        srptName = SSRSRequest.ReportNames.Purchasing.ReconciledMatchedAP; //"Pur_ReconcileMatched_AP";
                        break;

                    default:
                        throw new Exception(string.Format("User order type {0} is unknown or unsupported.",
                            ((OrderType) orderTypeID)));
                }

                ReconcileMatchedOrders matchedOrders = cachePolicy.GetCachedObject(ReconcileMatchedOrders.CacheKey) as ReconcileMatchedOrders;
                reportDataTable.Tables.Add(matchedOrders.Sort().Table);
                if (reportDataTable.Tables[0] == null)
                {
                    recordcount = reportDataTable.Tables[0].Rows.Count.ToString();
                }
                reporttitle = "Reconcile Matched";
            }
            else
            {
                switch (orderTypeID)
                {
                    case (int) OrderType.PurchaseOrder:
                        srptName = SSRSRequest.ReportNames.Purchasing.ReconciledUnMatchedPO; //"Pur_ReconcileUnMatched_PO";
                        break;
                    case (int) OrderType.JournalEntry:
                    case (int) OrderType.PettyCash:

                        srptName = SSRSRequest.ReportNames.Purchasing.ReconciledUnMatchedJE; //"Pur_ReconcileUnMatched_JE";
                        break;

                    case (int) OrderType.TravelVoucher:
                    case (int) OrderType.ChequeRequest:

                        srptName = SSRSRequest.ReportNames.Purchasing.ReconciledUnMatchedAP; //"Pur_ReconcileUnMatched_AP";
                        break;

                    default:
                        throw new Exception(string.Format("User order type {0} is unknown or unsupported.",
                            ((OrderType) orderTypeID)));
                }

                ReconcileUnMatchedOrders unMatchedOrders = cachePolicy.GetCachedObject(ReconcileUnMatchedOrders.CacheKey) as ReconcileUnMatchedOrders;
                reportDataTable = unMatchedOrders.GetDataContainer();
                if (reportDataTable.Tables[0] == null)
                {
                    recordcount = reportDataTable.Tables[0].Rows.Count.ToString();
                }
                reporttitle = "Reconcile Unmatched";
            }
        }

        /// <summary>
        /// Set Report Name based on the search criteria  for reconciliation
        /// </summary>
        private void SetReportNameAndDataSetForPOAPSummary(ref string srptName, ref DataSet reportDataTable, ref string reporttitle, ref string recordcount)
        {
            ICachePolicy cachePolicy = (ICachePolicy) Session[Names.CachePolicyKey];
            CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
            SearchCriteria commonSearchCriteria = searchContext.GetSearchCriteria(Page.Request["pageUrl"]);

            if (Convert.ToInt32(commonSearchCriteria[InsightUtilities.Constants.PurchasingSearchKey.SelectOrderViewKey]) == (int) OrderView.OrderSummary)
            {
                Transactions transactionSummaries = ResultsCache.GetObject(cachePolicy, POAPSummaries.CacheKey) as Transactions;
                reportDataTable = transactionSummaries.GetDataContainer();
                srptName = SSRSRequest.ReportNames.Common.POAPOrderSummary; //"Cmn_POAPOrderSummary";
                srptName = Request["fmt"] == "Excel" ? srptName + "Excel" : srptName;
                reporttitle = "PO/AP Summary";
                recordcount = reportDataTable.Tables[0].Rows.Count.ToString();
            }
            else
            {
                Transactions transactionSummaries = ResultsCache.GetObject(cachePolicy, POAPOrderDetails.CacheKey) as Transactions;
                reportDataTable = transactionSummaries.GetDataContainer();
                srptName = SSRSRequest.ReportNames.Common.POAPOrderDetail; //"Cmn_POAPOrderDetail";
                reporttitle = "PO/AP Summary";
                if (reportDataTable.Tables[1] == null)
                {
                    recordcount = reportDataTable.Tables[1].Rows.Count.ToString();
                }
            }
        }

        /// <summary>
        /// Loads the report object and sets the parameters appropriately.
        /// </summary>
        /// <returns>Report Document</returns>
        private Hashtable GetInputParameters(ref string srptName)
        {
            ICachePolicy cachePolicy = (ICachePolicy) Session[Names.CachePolicyKey];


            Hashtable tbl = new Hashtable();
            DataSet reportDataTable = new DataSet();
            string reporttitle = string.Empty;
            string recordcount = "";
            switch (srptName.ToLower())
            {
                case "poapsummaryreport":
                {
                    SetReportNameAndDataSetForPOAPSummary(ref srptName, ref reportDataTable, ref reporttitle, ref recordcount);
                    tbl.Add("reporttitle", reporttitle);
                }
                    break;
                case "poapdetails":
                {
                    POAPDetails poapDetails = ResultsCache.GetObject(cachePolicy, POAPDetails.CacheKey) as POAPDetails;
                    reportDataTable = PrepareTablesForDownload(poapDetails);

                    tbl.Add("reporttitle", "PO/AP Details");
                    srptName = SSRSRequest.ReportNames.Purchasing.PODetailsCollapsed; //"Pur_PODetailsCollapsed";
                }
                    break;
                case "reconcile":
                {
                    SetReportNameAndDataSetForReconciliation(ref srptName, ref reportDataTable, ref reporttitle, ref recordcount);
                    tbl.Add("reporttitle", reporttitle);
                }
                    break;
            }


            //Common code
            StringWriter sw = new StringWriter();
            reportDataTable.WriteXml(sw, XmlWriteMode.WriteSchema);

            tbl.Add("DataSource", sw.ToString());

            UserContext userContext = (UserContext) Session[UserContext.CacheKey];

            tbl.Add("recordcount", recordcount); //username
            tbl.Add("username", userContext.LastName + " " + userContext.FirstName); //username

            tbl.Add("filtercriteria", GetFilterCriteriaForReport(cachePolicy)); //filtercriteria

            tbl.Add("weburl", Settings.GetKeyValue("weburl", "http://insight2.partners.org")); //Domain User Id

            return tbl;
        }

        private DataSet PrepareTablesForDownload(POAPDetails POAPDetail)
        {
            DataTableCollection poDetailsTables = POAPDetail.GetDataContainer().Tables;
            DataSet trimmedPODetails = new DataSet();

            foreach (DataTable dataTable in poDetailsTables)
            {
                trimmedPODetails.Tables.Add(dataTable.Copy());
            }

            DataTable line = trimmedPODetails.Tables[Constants.POAPDetailsDataTableName];
            DataTable distribTable = trimmedPODetails.Tables[Constants.POAPDetailsDistribDataTableName];
            DataRowCollection distribRows = distribTable.Rows;
            foreach (DataRow distrib in distribRows)
            {
                DataRow[] expandedRows = line.Select(String.Format("{0} = {1} AND {2} = '{3}'",
                    Constants.IDColName, distrib[Constants.IDColName],
                    Constants.LineColName, distrib[Constants.LineColName]));

                foreach (DataRow expandedRow in expandedRows)
                {
                    line.Rows.Remove(expandedRow);
                }
            }
            trimmedPODetails.AcceptChanges();
            return trimmedPODetails;
        }

        private string GetFilterCriteriaForReport(ICachePolicy cachePolicy)
        {
            CommonSearchContext searchContext = cachePolicy.GetCachedObject(CommonSearchContext.CacheKey) as CommonSearchContext;
            if (searchContext != null)
            {
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(_pageUrl);
                return searchCriteria.ToString(";");
            }
            return string.Empty;
        }

        #endregion
    }
}